"use strict";

const Controller = require("egg").Controller;
const w = require("ws");
// const path = require("path")
const svgCaptcha = require('svg-captcha')

const fs = require("fs");
// const user = require("../../db/userSql.js");
// const nodemailer = require('nodemailer')
// var svgCaptcha = require('svg-captcha');
// const { url } = require('inspector');

class HomeController extends Controller {

  // 获取邮箱验证码
  // async sendCode(){
  //   // 验证码
  //   let code = Math.floor(Math.random()*900000)+100000
  //   // 建立一个smtp连接
  //   let transporter = nodemailer.createTransport({
  //     host:'smtp.qq.com',//
  //     secureConnection:true,
  //     post:465,//邮箱端口号
  //     auth:{
  //       user:'1647942360@qq.com',//自己的邮箱地址
  //       pass:'gmlfeszafpohcccd'//授权码
  //     }
  //   })
  //   // 配置相关参数
  //   let options = {
  //     from:'1647942360@qq.com',
  //     to:'1647942360@qq.com,',
  //     subject:'欢迎您',
  //     html:`
  //       <h1>尊敬的用户</h1>
  //               <p style="font-size: 18px;color:#000;">
  //               您的验证码为：
  //               <span style="font-size: 20px;color:#f00;"> ${code}， </span>
  //               您当前正在丁香医生网站注册账号，验证码告知他人将会导致数据信息被盗，请勿泄露
  //               </p>
  //               <p style="font-size: 1.5rem;color:#999;">该验证码5分钟内有效，请勿泄漏于他人！</p>
  //               `


  //   }
  //   transporter.sendMail(options,function(err,msg){
  //     if(err){
  //       console.log(err);
  //     }else {
  //       res.send(msg)
  //       transporter.close()
  //     }
  //   })
  // }


  // 获取用户登录成功时的缓存信息
  // async getUserInfo() {
  //   let phone = this.ctx.cookies.get("phone");
  // }

  // 用户登录
  async userlogin() {

    const { ctx } = this;
    // var ziduan = this.ctx.request.body;

    const ziduan = this.ctx.request.body;

    // console.log(ziduan);
    // 查询数据库中用户手机号是否存在
    let phonesql2 = `SELECT * FROM user_lx WHERE phone="${ziduan.phone}" `;
    let re2 = await this.app.mysql.query(phonesql2);
    if (!re2[0]) {
      this.ctx.body = { info: "手机号不存在", code: 4002 };
    } else {
      // 查询手机和密码是否都存在
      let sql2 = `SELECT * FROM user_lx WHERE phone="${ziduan.phone}" AND pwd="${ziduan.pwd}"`;
      let loginsql = await this.app.mysql.query(sql2);
      // console.log(loginsql[0]);
      if (loginsql[0]) {
        //数据库有数据表示登录成功
        // 设置缓存

        this.ctx.cookies.set("phone", ziduan.phone);
        this.ctx.cookies.set("uid",loginsql[0].uid);
        this.ctx.session.uid=loginsql[0].uid;
        this.ctx.session.username=loginsql[0].username;
        // this.ctx.cookies.set("username",loginsql[0].username);
        this.ctx.body = { info: "登录成功", code: 2002 };
        // 后端接收到前端传过来的数据，然后把账号密码加密为暗文（前端收到之后就把暗文存起来）下次前端请求服务器任何东西的时候直接把token码发过来就可以了
        // 创建令牌 加密


        this.ctx.body = { info: "ok666", code: 300,username:loginsql[0].username }

      } else {
        this.ctx.body = { info: "密码错误", code: 4003 };
      }
    }


  }

  // 用户注册
  async userregister() {
    // 字段
    let ziduan = this.ctx.request.body;
    console.log(ziduan);
    // 取出缓存验证码
    let verif = this.ctx.session.getverif
    if (ziduan.code != verif) {
      this.ctx.body = {
        info: '验证码输入不正确',
        code: 4011
      }
      return
    }

    // 查询手机是否注册过
    let usersql = `SELECT * FROM user_lx WHERE email="${ziduan.email}" `;
    let usersql2 = `SELECT * FROM user_lx WHERE phone="${ziduan.phone}"`;
    let re1 = await this.app.mysql.query(usersql);
    let rep = await this.app.mysql.query(usersql2)
    // console.log(re1);
    if (re1[0]) {
      this.ctx.body = { info: "邮箱已经注册", code: 4001 };
    } else if (rep[0]) {
      this.ctx.body = { info: "手机已经注册", code: 4004 };
    }
    else {
      // 没有注册过就插入数据
      let usersql = `INSERT INTO user_lx (username,phone,email,code,pwd,pwd2) VALUES ("${ziduan.username}","${ziduan.phone}","${ziduan.email}","${ziduan.code}","${ziduan.pwd}","${ziduan.pwd2}")`;
      let result = await this.app.mysql.query(usersql);
      console.log(result, 11111);
      this.ctx.body = { info: "注册成功", code: 2001 };
    }
    // 把账号和密码加密为暗文

  }

  // 管理员登录
  async adminlogin() {
    const { ctx } = this;
    var ziduan = this.ctx.request.body;
    console.log(ziduan);
    this.ctx.body = { info: "666", code: 200 }
    // 查询数据库中用户是否存在
    let adminsql = `SELECT * FROM admin WHERE adname="${ziduan.adname}" `;
    let adre = await this.app.mysql.query(adminsql);
    if (!adre[0]) {
      this.ctx.body = { info: "用户不存在", code: 4007 };
    } else {
      // 查询手机和密码是否都存在
      let sql2 = `SELECT * FROM admin WHERE adname="${ziduan.adname}" AND pwd="${ziduan.pwd}"`;
      let adloginsql = await this.app.mysql.query(sql2);
      if (adloginsql[0]) {
        //数据库有数据表示登录成功
        // 设置缓存
        this.ctx.cookies.set("adname", ziduan.adname);
        this.ctx.body = { info: "登录成功", code: 2006 };
      } else {
        this.ctx.body = { info: "密码错误", code: 4008 };
      }
    }
  }

  // 医生登录
  async doctorlogin() {
    const { ctx } = this;
    var ziduan = this.ctx.request.body;
    // if (!ziduan.title) {
    //   if (this.ctx.header.usertoken) {
    //     let token = this.ctx.header.usertoken
    //     const decode = await this.app.jwt.verify(token, this.app.config.jwt.secret);
    //     this.ctx.user = {
    //       username: decode.username,
    //       uid: decode.uid,
    //       phone: decode.phone,
    //       email: decode.email,
    //       pwd: decode.pwd,
    //     }
    //     let phoneSQL = `SELECT * FROM user_lx WHERE phone="${this.ctx.user.phone}" `;
    //     let re = await this.app.mysql.query(phoneSQL);
    //     if (!re[0]) {
    //       this.ctx.body = { info: "手机号不存在", code: 4002 };
    //       return
    //     } 
  
    //       const rep = {
    //         username: decode.username
    //       }
    //       this.ctx.body = { info: "令牌验证成功", code: 4001, rep };
          
        
    //   }
    // }
    

    // this.ctx.body = { info: "111666", code: 200 }
    // 查询数据库中医生用户是否存在
    let doctorsql = `SELECT * FROM goods WHERE zhanghao="${ziduan.zhanghao}" `;
    let docre = await this.app.mysql.query(doctorsql);
    if (!docre[0]) {
      this.ctx.body = { info: "该医生不存在", code: 4005 };
    } else {
      // 查询账号和密码是否都存在
      let sql2 = `SELECT * FROM goods WHERE zhanghao="${ziduan.zhanghao}" AND mima="${ziduan.mima}"`;
      let docloginsql = await this.app.mysql.query(sql2);
      if (docloginsql[0]) {
        //数据库有数据表示登录成功
        // 设置缓存
        this.ctx.cookies.set("adname", ziduan.adname);
        this.ctx.body = {
           info: "登录成功",
            code: 2008 ,
            id:docloginsql[0].id,
            img:docloginsql[0].img,
            doctorName:docloginsql[0].title
          };
        // console.log(docloginsql[0]);
        // const UserToken = this.app.jwt.sign(
        //   {
        //     username: loginsql[0].username,
        //     uid: loginsql[0].uid,
        //     phone: loginsql[0].phone,
        //     email: loginsql[0].email,
        //     pwd: loginsql[0].pwd,
        //   }, this.app.config.jwt.secret, {
        //   expiresIn: this.app.config.jwt.expiresIn, //过期时间
        // });
      } else {
        this.ctx.body = { info: "密码错误", code: 4009 };
      }
    }
  }

  // 验证码
  async getverif() {
    // 生成验证码
    var captcha = svgCaptcha.create({
      size: 4,
      color: true,
      background: 'grey'
    })
    // 设置缓存
    this.ctx.session.getverif = captcha.text
    // 发送给前端
    this.ctx.body = captcha.data
  }

}

module.exports = HomeController;
